﻿/// <reference path="jquery3.js" />

if(!window.$$Shell) window.$$Shell = {};
$$.Shell = new function () {
    var me = this;

    var gidx = 1000;
    var gidx1 = -1000;
    var callbacks = {};

    function emptyfunc(){}

    function addCallback(callback) {
        if (!callback) return 0;
        var guid = gidx++;
        callbacks[guid + ""] = callback;
        return guid;
    }
    me._addCallback = addCallback;

    function execShell(func, params, guid) {
        if (!func) return;
        var ps = "";
        if (params) ps = window.encodeURI($$.Jsonar.stringify(params, 9));
        if (!guid) guid = gidx1--;
        var href = "/$/" + func + "?" + guid + "#" + ps;
        var img = new Image();
        img.src = href;
        img = null;
    }
    me._exec = execShell;
     
    //获取当前经纬度
	//callback(rst,lat,lng)
	//rst:true/错误信息
    me.Gps = function(callback) {
        if (!callback) callback = emptyfunc;
        if ($$Shell.Gps !== 1) { callback(); return; }
        var guid = addCallback(callback);
        execShell("Gps", null, guid);
    };

    //打开第三方地图
    function map(label) {
        if (!label) return false;
        me.OpenBrowser("http://map.baidu.com/mobile/webapp/place/linesearch/foo=bar/from=place&tab=line&end=word%3D" + window.encodeURI(label) + "%26");
        return true;
    }
    me.Map = function (lat, lng, label, callback,area) {
        if (!callback) callback = emptyfunc;
        if ($$Shell.Map !== 1) { callback(map(label)); return; }
        var guid = addCallback(function (rst) {
            if (!rst) callback(map(label));
            else callback(true);
        });
        execShell("Map", { lat: lat, lng: lng, label: label }, guid);
    };

    //获取当前网络状态
    //refresh：强制刷新
    //callback(rst)：回调函数
    //rst：网络状态结果
    //-1：无网络
    // 0：未知
    // 1：wlan
    // 2：数据    此状态看视频应询问
    /**
     * 
     * @param {*} refresh 
     * @param {*} callback 
     */
    me.NetState = function (refresh, callback) {
        if (!callback) callback = emptyfunc;
        if ($$Shell.NetState !== 1) { callback(0); return; }
        var guid = addCallback(callback);
        execShell("NetState", { refresh: refresh ? true : false }, guid);
    };

    //清空缓存
    me.ClearCache = function (callback) {
        if (!callback) callback = emptyfunc;
        if ($$Shell.ClearCache !== 1) { callback(); return; }
        var guid = addCallback(callback);
        $$.DB.Clear("**", true);
        execShell("ClearCache", null, guid);
    };


    //震动
    me.Vibrate = function () {
        if ($$Shell.Vibrate !== 1) return;
        execShell("Vibrate");
    };

    //提醒声音
    //vibreate 同时震动
    me.Dudu = function (vibrate) {
        if ($$Shell.Dudu !== 1) return;
        execShell("Dudu", { vibrate: vibrate });
    };


    var imgMime = "image/jpeg";
    function dealImage(url, option, callback) {
        if (!option) option = {};
        function calc(w, h) {
            var cw = option.width || 600;
            var ch = option.height || 0;
            if (ch <= 0) {
                if (w <= cw) return { w: w, h: h, cw: w, ch: h, x: 0, y: 0 };
                return { w: w, h: h, cw: cw, ch: h / w * cw, x: 0, y: 0 };
            }
            if (w <= cw && h <= ch) return { w: w, h: h, cw: w, ch: cw * h / w, x: 0, y: 0 };

            var s = w / h, cs = cw / ch, x = 0;
            if (s < cs - 0.2) {
                s = cs - 0.2;
                h = w / s;
                ch = cw / s;
            }
            else if (s > cs + 0.2) {
                s = cs + 0.2;
                var n = h * s;
                x = (w - n) / 2;
                w = n;
                cw = ch * s;
            }
            if (cw > w) {
                cw = w;
                ch = cw / s;
            }
            if (ch > h) {
                ch = h;
                cw = ch * s;
            }
            return { w: w, h: h, cw: cw, ch: ch, x: x, y: 0 };
        }
        function deal1(img) {
            var wh = calc(img.width, img.height);
            var cv = document.createElement("canvas");
            cv.width = wh.cw;
            cv.height = wh.ch;
            try {
                var ctx = cv.getContext("2d");
                ctx.drawImage(img, wh.x, wh.y, wh.w, wh.h, 0, 0, wh.cw, wh.ch);
            }
            catch (ex) { callback(); }
            deal2(cv);
        }
        function deal2(cvs) {
            var ms = (option.size || 1000) * 1024;
            var n = 1.0;
            var b64 = cvs.toDataURL(imgMime, 0.85);
            if (!b64) { callback(); return; }
            $$.BlobToUrl(b64, imgMime, function (url) {
                callback(url);
            })
        }

        if (!url || url.length < 3) { callback(); return; };
        var img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = function () { callback(); };
        img.onload = function () { deal1(img); }
        img.src = url;
    };

    //从手机原生程序选择图片
    //option 图片处理属性，包含
    //cut：true时裁剪
    //callback ，选择的回调函数 func(rst)
    //rst 返回结果对象
    //rst.url 返回的本地图片地址
    me.SelImg = function (callback, option) {
        if (!callback) callback = emptyfunc;
        if (!$$Shell.SelImg !== 1) { callback(); return; }
        var guid = addCallback(function (rst) {
            if (!rst || !rst.success || !rst.url) { callback(); return; }
            dealImage(rst.url, option, function (url) {
                if (url) callback({ url: url });
                else callback();
            });
        });
        execShell("SelImg", null, guid);
    };

    //从手机原生程序拍照获取图片
    //与SelImg使用相同
    me.CameraImg = function (callback, option) {
        if (!callback) callback = emptyfunc;
        if ($$Shell.CameraImg !== 1) { callback(); return; }
        var guid = addCallback(function (rst) {
            if (!rst || !rst.success || !rst.url) { callback(); return; }
            dealImage(rst.url, option, function (url) {
                if (url) callback({ url: url });
                else callback();
            });
        });
        execShell("CameraImg", null, guid);
    };
    //从手机原生程序选择多个图片
    //与SelImg使用相同
    //区别是返回rst.urls数组
    me.SelImgs = function (callback, option) {
        if (!window.$$Shell || $$Shell.SelImgs !== 1) { if (callback) callback(); return; }
        var guid = addCallback(function (rst) {
            if (!rst || !rst.success || !rst.urls || rst.urls.length < 1) { callback(); return; }
            var idx = 0, urls = [], uris = rst.urls;
            function exec() {
                if (idx >= uris.length) {
                    if (urls.length > 0) callback({ success: true, urls: urls });
                    else callback();
                    return;
                }
                var uri = uris[idx++];
                if (!uri) { exec(); return; }
                dealImage(uri, option, function (url) {
                    if (url) urls.push(url);
                    exec();
                });
            }
            exec();
        });
        execShell("SelImgs", null, guid);
    };



	var UploadHost = "http://daili.renwuto.cn";
	var UploadUrl = UploadHost + "/api/Upload/File?";
    function upImage(fdata, subdir, callback) {
        var called = false;
        var url = UploadUrl + "tk=" + $$.Vis.Token();
        if (subdir) url += "&sub=" + subdir;
        $.ajax({
            method: "POST",
            url: url,
            data: fdata,
            dataType: "text",
            processData: false,
            contentType: false,
            success: function (text) {
                called = true;
                var rst = $$.Jsonar.parse(text);
                if (rst && rst.url) callback(UploadHost + rst.url);
                else callback();
            },
            error: function (a, b, err) { called = true; callback(); },
            complete: function () { if (!called) callback(); },
            async: true,
            global: false
        });
    }
    //上传图片
    //uri：本地图片url
    //-------
    //callback ，上传的回调函数 function(rst)
    //rst 返回结果对象，包括
    //success：是否成功
    //url： 网络图片地址
    //mess： 输出消息
    me.UpImg = function (uri, callback, subdir) {
        if (!callback) callback = emptyfunc;
        if (!uri || uri.length < 3) { callback(); return; }
        $$.UrlToBlob(uri, imgMime, function (blob) {
            if (!blob) { callback(); return; }
            var fdata = new FormData();
            fdata.append("file", blob, "1.jpg");
            upImage(fdata, subdir, function (url) {
                if (!url) callback();
                else callback({ success: true, url: url, size: blob.size });
            });
        });
    };
    //上传多个图片
    //uris：本地图片地址数组
    //-------
    //callback ，上传的回调函数 function(rst)
    //rst 返回结果对象，包括
    //success：是否成功
    //urls： 网络图片地址数组
    //mess： 输出消息
    me.UpImgs = function (uris, callback, subdir) {
        if (!callback) callback = emptyfunc;
        if (!uris || uris.length < 1) { callback(); return; }
        var idx = 0, urls = [];
        function exec() {
            if (idx >= uris.length) {
                if (urls.length > 0) callback({ success: true, urls: urls });
                else callback();
                return;
            }
            var uri = uris[idx++];
            if (!uri) { exec(); return; }
            $$.UrlToBlob(uri, imgMime, function (blob) {
                if (!blob) { exec(); return; }
                var fdata = new FormData();
                fdata.append("file", blob, "1.jpg");
                upImage(fdata, subdir, function (url) {
                    if (url) urls.push({ url: url, size: blob.size });
                    exec();
                });
            });
        }
        exec();
    };

    //将图片保存到相册
    //b64：base64格式的图片内容
    //name：要保存图片的名字，不含扩展名，可省略
    //callback(rst)：回调函数，rst为true表示保存成功
    me.SaveImgB64 = function (b64, name, callback) {
        if (!window.$$Shell || $$Shell.SaveImgB64 !== 1) { if (callback) callback(); return; }
        if (!b64 || typeof b64 !== "string") { if (callback) callback(); return; }
        var idx = b64.indexOf(",", 0);
        if (idx >= 0) b64 = b64.substr(idx + 1);
        b64 = b64.replace(/\s+/g, '');
        if (!b64 || b64.length < 5) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("SaveImgB64", { b64: b64, title: name }, guid);
    };

    //上传文件到OSS，一般是语音或视频文件
    //local：app本地文件，一般是/@开头的路径
    //subdir：在oss上的子目录
    //ext：要保存的扩展名
    //mime：响应的mime
    me.UpOss = function (local, callback, subdir, ext, mime) {
        if (!local) { if (callback) callback(); console.error("Shell.UpOss local未指定"); return; }
        if (!window.$$Shell || $$Shell.UpOss !== 1) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("UpOss", {local:local, sub:subdir, ext:ext, mime:mime}, guid);
    };

    //从手机原生程序获取视频
    //option 视频属性,暂无
    //-------
    //callback ，选择的回调函数 function(rst)
    //rst 返回结果对象
    //rst.cover
    //rst.time
    //rst.url 返回的本地视频地址
    me.MakeVideo = function (callback, option) {
        if (!window.$$Shell || $$Shell.MakeVideo !== 1) { if (callback) callback(); return; }
        //if (!option) option = {};
        var guid = addCallback(callback);
        //var sec = option.second || 0;
        execShell("MakeVideo", null, guid);
    };

    //支付宝支付
    //BillType:4=支付宝,3=账户余额,12=微信
    //Order：订单编号
    //UseTubi: 是否使用兔币, 布尔值
    //Price: 金额, 可选
    //repay:正常支付0，继续支付1
    me.Alipay = function (order, usetubi, BillType, Price, repay, callback) {
        if (!window.$$Shell || $$Shell.Alipay !== 1) { callback({ memo: "启动支付宝失败" }); return; }
        var tmp = { 'Order': order, 'UseTubi': usetubi, BillType: BillType, repay: repay };
        if (Price) {
            tmp.Price = Price;
        }
        $$.GetData('alipay/payfee', tmp, function (rst) {
            if (!rst) rst = {};
            if (!rst.success) {
                callback({ memo: "初始化支付出错" });
                return;
            }
            if (!rst.row) {
                callback();
                return;
            }
            var guid = addCallback(function (payData) {
                if (!payData) payData = "";
                if (payData.indexOf('resultStatus') > -1 && payData.indexOf('9000') > -1) {
                    $$.Page.Open("Order_AliPaySucc", { payData: payData }, function (val) {
                        callback({ resultStatus: 9000, trade_no: val.trade_no });
                    });
                } else {
                    callback();
                }
            });
            execShell("Alipay", { payinfo: rst.row.TN }, guid);
        });
    };

    //支付宝认证
    me.Renzheng = function (callback) {
        if (!window.$$Shell || $$Shell.Alipay !== 1) { callback({ memo: "启动支付宝失败" }); return; }
        $$.GetData('alipay/renzheng', {}, function (rst) {
            if (!rst) rst = {};
            if (!rst.success) {
                callback({ memo: "初始化出错" });
                return;
            }
            if (!rst.row) {
                callback();
                return;
            }
            var guid = addCallback(function (payData) {
                if (!payData) payData = "";
                if (payData.indexOf('resultStatus') > -1 && payData.indexOf('9000') > -1) {
                    callback({ resultStatus: 9000 });
                    $$.Page.Open("Order_AliPaySucc", { payData: payData });
                } else {
                    callback();
                }
            });
            console.log(rst.row.TN);
            execShell("Alipay", { payinfo: rst.row.TN }, guid);
        });
    }

    //拨打电话
    me.DialPhoneTest = function (phone, fromid, toid) {
        if (!window.$$Shell || $$Shell.DialPhone !== 1) { $$.Tips("启动电话失败"); return; }
        execShell("DialPhone", { phone: phone, f: fromid, t: toid });
    };

    //拨打电话
    me.DialPhone = function (phone, fromid, toid) {
        if (!window.$$Shell || $$Shell.DialPhone !== 1) { $$.Tips("启动电话失败"); return; }
        $$.Vis.IsLogon(true, function (rst) {
            if (rst === true) execShell("DialPhone", { phone: phone, f: fromid, t: toid });
        });
    };

    //拨打用户电话
    me.DialID = function (fromid, toid) {
        if (!window.$$Shell || $$Shell.DialID !== 1) { $$.Tips("启动电话失败"); return; }
        $$.Vis.IsLogon(true, function (rst) {
            if (rst === true) execShell("DialID", { f: fromid, t: toid });
        });
    };

    //拨打B2C电话
    me.DialB2C = function (fromid, toid) {
        if (!window.$$Shell || $$Shell.DialPhone !== 1) { $$.Tips("启动电话失败"); return; }
        toid = $$.ParseInt(toid);
        if (!toid || toid < 400000 || toid >= 500000) { $$.Tips("不是品牌商家"); return; }
        $$.Vis.IsLogon(true, function (rst) {
            if (rst === true) $$.GetSver(toid, function (sver) {
                if (!sver || !sver.Service || !sver.Service.Mobile) { $$.Tips("品牌商家号码无效"); return; }
                if (rst === true) execShell("DialPhone", { phone: sver.Service.Mobile, f: fromid, t: toid });
            });
        });
    };

    //打开外部链接
    //title：标题栏内容
    me.OpenLink = function (url, title) {
        if (!url) return;
        if (!window.$$Shell || $$Shell.OpenLink !== 1) {
            $$.Page.Open('Pub_ViewLink', { 'src': url });
            return;
        }
        execShell("OpenLink", { url: url, title: title });
    };

    //浏览器打开外部链接
    me.OpenBrowser = function (url) {
        if (!url) return;
        if (!window.$$Shell || $$Shell.OpenBrowser !== 1) {
            $$.Page.Open('Pub_ViewLink', { 'src': url });
            return;
        }
        execShell("OpenBrowser", { url: url });
    };

    //复制到剪贴板
    //callback(rst)    rst:true/false
    me.Copy2Clip = function (txt, callback) {
        if (!txt || !window.$$Shell || $$Shell.Copy2Clip!==1) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("Copy2Clip", { txt: txt + "" }, guid);
    };

    //判断是否存在第三方app
    //回调callback(rst)
    //rst == true时存在
    //方法传递的参数appid是类似 com.renwuto.ios这样的字符串
    me.AppHas = function (appid, callback) {
        if (!appid || !window.$$Shell || $$Shell.AppHas !== 1) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("AppHas", { pidx:6, lsa: "LS", apl: "ppli", appid: appid + "" }, guid);
    };

    //判断是否存在多个第三方app
    //回调callback(rst)
    //rst：Array，存在的appid数组
    me.AppHass = function (appids, callback) {
        if (!appids || appids.length < 1 || !window.$$Shell || $$Shell.AppHass !== 1) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("AppHass", { pidx:6, lsa:"LS", apl: "ppli", appids: appids }, guid);
    };

    //打开第三方app
    //回调callback(rst)
    //rst == true时成功
    me.AppOpen = function (appid, callback) {
        if (!appid || !window.$$Shell || $$Shell.AppOpen !== 1) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("AppOpen", { pidx:6, lsa: "LS", apl: "ppli", appid: appid + "" }, guid);
    };

    //判断没有越狱
    //回调callback(rst)
    //rst == true 未越狱
    me.Jailin = function (callback) {
        if (!window.$$Shell || $$Shell.Jailin !== 1) { if (callback) callback(true); return; }
        var guid = addCallback(callback);
        execShell("Jailin", null, guid);
    };

    //显示本地推送通知
    //text：推送正文
    //title：推送标题
    //icon：图标url，尽量使用https
    //cata：推送分类，Int，分类相同的通知可能会折叠在一起
    //page: 推送页面，点击推送消息启动APP，然后打开这个页面
    me.SendNotify = function (text, title, icon, cata, page) {
        if (!text) return;
        if (!window.$$Shell || $$Shell.SendNotify !== 1) {
            if (title) text = "<b>" + title + "</b><br/>" + text;
            $$.Tips(text, 3, true, 0, true);
            return;
        }
        if (!title) title = "";
        if (!cata) cata = "";
        if (!icon) icon = "";
        if (!page) page = "";
        execShell("SendNotify", { text: text + "", title: title + "", cata: cata + "", icon: icon + "", page: page + "" });
    };

    //SNS分享
    //callback(rst)
    //rst：>0 完成；0 失败； -9 未安装SNS客户端； -99 需安装任务兔客户端；<0 取消
    me.ShareSNS = function (target, params, callback) {
        if (!window.$$Shell || $$Shell.ShareSNS !== 1 || !params) { if (callback) callback(); return; }
        target = $$.ParseInt(target);
        if (!(target > 0)) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("ShareSNS", { target: target, params: params }, guid);
    };
    //SNS授权
    //params：登录成功后自动分享的内容，与ShareSNS一样
    me.AuthSNS = function (target, callback, params) {
        if (!window.$$Shell || $$Shell.AuthSNS !== 1) { if (callback) callback(); return; }
        target = $$.ParseInt(target);
        if (!(target > 0)) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("AuthSNS", { target: target, params: params }, guid);
    };
    //SNS解除授权
    me.UnAuthSNS = function (target, callback) {
        if (!window.$$Shell || $$Shell.UnAuthSNS !== 1) { if (callback) callback(); return; }
        target = $$.ParseInt(target);
        if (!(target > 0)) { if (callback) callback(); return; }
        var guid = addCallback(callback);
        execShell("UnAuthSNS", { target: target }, guid);
    };

    me.PubKey = function (callback) {
        var key = '';
        if ($$.IsIOS == true) {
            key = 'f2456c738878fab6317718a41414589d';
        } else {
            key = '3fdd7d5658ba0fe723bd2bf91b5c5a03';
        }
        if (callback) {
            callback(key);
        }
        return;
        //if (!window.$$Shell || $$Shell.PubKey !== 1) { if (callback) callback(null); return 0; }
        //var guid = addCallback(callback);
        //execShell("PubKey", null, guid);
    };

    me.IMStart = function (params) {
        if (!window.$$Shell || $$Shell.IMStart !== 1 || !params) { $$.IM.OnLogin(false); return; }
        execShell("IMStart", params);
    };

    me.IMLogout = function () {
        if (!window.$$Shell || $$Shell.IMLogout !== 1) { $$.IM.OnLogout(false); return; }
        execShell("IMLogout");
    };

    me.IMSendMsg = function (msg, callback) {
        if (!window.$$Shell || $$Shell.IMSendMsg !== 1 || !msg) { if (callback) callback(); return false; }
        var guid = addCallback(callback);
        execShell("IMSendMsg", msg, guid);
    };

    window.$$App = new function () {
        var my = this;

        function backCall(guid, params) {
            if (!guid || guid > -1000) return;
            execShell("_shlbkcall", params, guid);
        }

        my.$backcall = function (guid, params) {
            if (!guid || guid < 1000) return;
            var func = callbacks[guid + ""];
            if (!func) return;
            delete callbacks[guid + ""];
            func(params);
        };

        my.GoBack = function (params, guid) {
            var suc = $$.Page.CloseCur();
            backCall(guid, suc);
        };

        my.Tips = function (params) {
            if (!params) return;
            $$.Tips(params.mess, params.second, params.animatenone, params.position);
        };

        my.Token = function (params, guid) {
            var token = $$.Vis.Token();
            if (token) {
                backCall(guid, token);
                return;
            }
            $$.Vis.IsLogon(false, function () {
                token = $$.Vis.Token();
                backCall(guid, token);
            });
        };
    };
};